import Vue from "vue";
import Vuex from "vuex";
import util from "../Logic/Util.js";
Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    userInfo: JSON.parse(sessionStorage.getItem("userInfo")) || {},
    token: sessionStorage.getItem("token") || ""
  },
  mutations: {
    setToken: (state, payload) => {
      let res = util.decode(payload); //解析token
      window.console.log(res);
      if (res) {
        state.userInfo = res;
        state.token = payload;
        sessionStorage.setItem("token", JSON.stringify(payload));
        sessionStorage.setItem("userInfo", JSON.stringify(res));
      }
    },

    clearToken: state => {
      sessionStorage.removeItem("token");
      sessionStorage.removeItem("userInfo");
      state.userInfo = {};
      state.token = "";
    }
  },
  actions: {
    updateToken(context, value) {
      context.commit("setToken", value);
    }
  }
});
